<template>
  <div class="classroom-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>教室管理</span>
          <el-button v-permission="['editClassroom']" type="primary" @click="handleAdd">新增教室</el-button>
        </div>
      </template>

      <el-table 
        :data="classroomList" 
        border 
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <el-table-column prop="avatar" label="教室图片" width="120">
          <template #default="{row}">
            <el-image :src="row.avatar" fit="cover" style="width: 80px; height: 60px" />
          </template>
        </el-table-column>
        <el-table-column prop="classroomName" label="教室名称" width="150" />
        <el-table-column prop="description" label="教室描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" v-permission="['editClassroom']">
          <template #default="{row}">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
      <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
        <el-form-item label="教室名称" prop="classroomName">
          <el-input v-model="form.classroomName" />
        </el-form-item>
        <el-form-item label="教室图片" prop="avatar">
          <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'Authorization': `Bearer ${getToken()}` }"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <div v-else class="uploader-placeholder">
              <el-icon class="avatar-uploader-icon">
                <Plus />
              </el-icon>
              <div class="uploader-text">点击上传教室图片</div>
              <div class="uploader-hint">建议尺寸：800×600，大小不超过2MB</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="教室描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="1">启用</el-radio>
            <el-radio value="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { getClassroomListAll, addClassroom, updateClassroom, delClassroom } from '@/api/classroom'

const classroomList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增教室')
const formRef = ref()
const form = reactive({
  id: '',
  classroomName: '',
  avatar: '',
  description: '',
  status: '1'
})

const rules = reactive({
  classroomName: [
    { required: true, message: '请输入教室名称', trigger: 'blur' }
  ],
  avatar: [
    { required: true, message: '请上传教室图片', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入教室描述', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 获取教室列表
const getClassroomList = async () => {
  loading.value = true
  try {
    const res = await getClassroomListAll()
    classroomList.value = res.data
  } catch (error) {
    ElMessage.error('获取教室列表失败')
  } finally {
    loading.value = false
  }
}

// 新增教室
const handleAdd = () => {
  dialogTitle.value = '新增教室'
  Object.assign(form, {
    id: '',
    classroomName: '',
    avatar: '',
    description: '',
    status: '1'
  })
  dialogVisible.value = true
}

// 编辑教室
const handleEdit = (row) => {
  dialogTitle.value = '编辑教室'
  form.id = row.id
  form.classroomName = row.classroomName
  form.avatar = row.avatar
  form.description = row.description
  form.status = row.status
  dialogVisible.value = true
}

// 删除教室
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该教室吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await delClassroom(row.id)
      ElMessage.success('删除成功')
      getClassroomList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    if (form.id) {
      // 编辑
      await updateClassroom(form)
    } else {
      // 新增
      await addClassroom(form)
    }
    dialogVisible.value = false
    ElMessage.success('操作成功')
    getClassroomList()
  } catch (error) {
    if (!error || error.toString().includes('validation')) {
      return // 不显示验证错误消息
    }
    ElMessage.error('操作失败')
  }
}

// 头像上传成功处理
const handleAvatarSuccess = (response, file) => {
  console.log(response, URL.createObjectURL(file.raw))
  form.avatar = response.data
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) {
    ElMessage.error('您上传的不是图片!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

onMounted(() => {
  getClassroomList()
})
</script>

<style scoped>
.classroom-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 500px;
  height: audo;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  text-align: center;
  margin-bottom: 8px;
}

.uploader-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.uploader-text {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin-bottom: 4px;
}

.uploader-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>